package com.bwie.sixth.house.controller;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;


import com.bwie.sixth.house.config.JwtUtil;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.bwie.sixth.house.entity.AdminEntity;
import com.bwie.sixth.house.service.AdminService;




/**
 * 
 *
 * @author lzl
 * @email 1601711944@gmail.com
 * @date 2021-10-16 09:57:43
 */
@Slf4j
@RestController
@RequestMapping("house/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 列表
     */
    @RequestMapping("/list")

    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = adminService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{adminId}")

    public R info(@PathVariable("adminId") Integer adminId){
		AdminEntity admin = adminService.getById(adminId);

        return R.ok().put("admin", admin);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")

    public R save(@RequestBody AdminEntity admin){
		adminService.save(admin);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")

    public R update(@RequestBody AdminEntity admin){
		adminService.updateById(admin);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")

    public R delete(@RequestBody Integer[] adminIds){
		adminService.removeByIds(Arrays.asList(adminIds));

        return R.ok();
    }


    @PostMapping("/login")
    public R login(@RequestBody AdminEntity adminEntity){
        AdminEntity login = adminService.login(adminEntity);
        if(login != null){
            String token = jwtUtil.createJWT(String.valueOf(login.getAdminId()), login.getAdminName(), "user");
            System.out.println(token);
            stringRedisTemplate.opsForValue().set("token"+login.getAdminId(),token,30, TimeUnit.MINUTES);
            return R.ok().put("token",token).put("login",login);
        }
        return R.error().put("msg","登录失败");
    }
}